package com.cyx.exam.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.cyx.exam.entity.Class;
import com.cyx.exam.service.ClassService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * @author cyx
 * @create 2021-03-22 16:41
 */
@Controller
@RequestMapping("/class")
public class ClassController {

    @Resource
    private ClassService classService;

    @GetMapping("/list")
    public String view(@RequestParam(required = false, defaultValue = "1", value = "pn") Integer pn,
                       Model model) {
        IPage<Class> page = classService.selectByPage(pn, 5);
        model.addAttribute("jumpUrl", "list?pn=");
        //此处得到的page对象,包含了current（当前页）,pages（总页数），total（总记录数），records（记录，就是查询到的List集合）
        model.addAttribute("page", page);
        return "class/list";
    }
    @GetMapping("/searchsubmit")
    public String searchsubmit(@RequestParam(required = false, defaultValue = "", value = "name")String name,
                               Model model,
                               @RequestParam(required = false, defaultValue = "1", value = "pn") Integer pn) {
        IPage<Class> page = classService.searchByPage(pn, 5, name);
        model.addAttribute("jumpUrl", "list?name="+name+"&pn=");
        model.addAttribute("page", page);
        return "class/list";
    }
    @GetMapping({"/edit/{id}","/edit"})
    public String insert(@PathVariable(value = "id",required = false) Integer id,Model model){
        Class aClass = new Class();
        if(id!=null){
            aClass = classService.getById(id);
            model.addAttribute("type","update");
        }else{
            model.addAttribute("type","insert");
        }
        model.addAttribute("class",aClass);
        return "class/edit";
    }

    @PostMapping("/update/{type}")
    public String saveOrUpdate(Class aclass,@PathVariable("type") String type,Model model){
        Class aClass = classService.getOne(new QueryWrapper<Class>().lambda().eq(Class::getName, aclass.getName()));
        if(aClass != null && type.equals("insert")){
            model.addAttribute("msg","该班级已存在");
            return "class/edit";
        }
        classService.saveOrUpdate(aclass);
        return "redirect:/class/list";
    }

    @GetMapping("/del/{id}")
    public String delete(@PathVariable(value = "id") Integer id){
        classService.delete(id);
        return "redirect:/class/list";
    }
}
